﻿using System;
using System.Web;

namespace K3R.SqlLogging {
	public class LogModule : IHttpModule {
		Log log = null;

		public void Init(HttpApplication context) {
			log = new Log(Settings.ConnectionString, Settings.Source);

			if (Settings.LogAllEvents)
				context.LogRequest += new EventHandler(OnLogRequest);

			context.Error += new EventHandler(OnError);
			//context.PostAuthenticateRequest += new EventHandler(OnPostAuthenticateRequest);

			//log.Info("Application Started");
		}

		public void Dispose() {}

		public void OnLogRequest(Object source, EventArgs e) {
			log.Info("Test Log");
		}

		public void OnError(object sender, EventArgs e) {
			HttpContext context = HttpContext.Current;
			log.Error("{0}, {1}, {2}, {3}", context.Request.FilePath, context.Request.UserHostAddress,
				context.Request.UserAgent, context.Server.GetLastError());
		}

		public void OnPostAuthenticateRequest(object sender, EventArgs e) {
			HttpContext context = HttpContext.Current;

			log.Info("{0} Authenticated.", context.User.Identity.Name);
		}
	}
}
